<template>
  <div class="q-pa-md text-bold" style="font-size: 1.4em">
    <q-icon name="stars" size="sm" color="blue-8" class="q-mr-sm" />
    <span>导入物料信息</span>
  </div>
  <q-stepper
    v-model="step"
    header-nav
    ref="stepper"
    color="primary"
    animated
    keep-alive
  >
    <q-step
      :name="1"
      title="选择文件"
      icon="settings"
      :done="step > 1"
      :header-nav="step > 1"
    >
      <readFromFile uid="importMaterial" :titleLine="1" :dataLine="2" ref="readFile" />

      <q-stepper-navigation class="flex justify-center">
        <q-btn @click="step1" color="primary" label="下一步" />
        <q-btn label="返回" @click="goBack" color="primary" outline class="q-ml-md bg-white" />
      </q-stepper-navigation>
    </q-step>

    <q-step
      :name="2"
      title="数据预览"
      icon="create_new_folder"
      :done="step > 2"
      :header-nav="step > 2"
    >
      <previewData uid="importMaterial" ref="preview" />

      <q-stepper-navigation class="flex justify-center">
        <q-btn @click="step2" color="primary" label="下一步" />
        <q-btn flat @click="step = 1" color="primary" label="上一步" class="q-ml-sm" />
        <q-btn label="返回" @click="goBack" color="primary" outline class="q-ml-md bg-white" />
      </q-stepper-navigation>
    </q-step>

    <q-step
      :name="3"
      title="数据校验"
      icon="add_comment"
      :header-nav="step > 3"
    >
      <div class="row justify-center q-my-md">
        <q-input
          dense
          class="col-lg-4 col-md-6 col-xs-10"
          filled
          label="数据相似度"
          v-model="simStandard"
          type="number"
          hint="数值介于0~1之间的小数"
          max="1"
          min="0"
          step="0.1"
        >
        </q-input>
        <div>
          <q-btn color="primary" dense label="重新匹配" @click="similarity(data)" :loading="loading" />
        </div>
      </div>

      <q-linear-progress size="10px" :value="progress" v-show="progress < 1" />

      <q-table
        :grid="$q.screen.xs"
        :rows="data"
        :columns="columns"
        row-key="id"
        :rows-per-page-options="[0]"
        v-model:pagination="pagination"
        binary-state-sort
        separator="cell"
        selection="multiple"
        v-model:selected="selected"
        :style="$q.screen.xs ? '' : 'max-height: calc(100vh - 100px)'"
        class="my-sticky-virtscroll-table"
      >
        <template v-slot:body="props">
          <q-tr :props="props" :class="props.selected && 'bg-blue text-white'">
            <q-td auto-width>
              <q-checkbox v-model="props.selected" :disable="checkDisabled(props.row)">
                <q-tooltip v-if="checkDisabled(props.row)">有完全相同的数据(相似度1)，禁止导入重复数据</q-tooltip>
              </q-checkbox>
            </q-td>
            <q-td :key="col.name" :props="props" v-for="col in props.cols" auto-width>
              {{ col.value }}
            </q-td>
          </q-tr>
          <q-tr :props="props">
            <q-td colspan="100%" class="bg-grey-1">
              <div class="q-py-sm">
                <q-bar dark class="bg-green-4">
                  <div>数据校对</div>
                </q-bar>

                <div class="row q-py-xs q-gutter-sm">
                  <q-input
                    v-for="field in fields" :key="field.value"
                    dense
                    class="col-lg-3 col-md-3 col-xs-10"
                    filled
                    v-model="props.row[field.value]"
                    :label="field.label"
                    :disable="!props.selected"
                  />
                </div>
              </div>

              <div class="q-py-sm">
                <q-bar dark class="bg-orange-4">
                  <div>相似数据</div>
                </q-bar>
                <q-table
                  v-if="props.row.detail && props.row.detail.length > 0"
                  dense
                  flat
                  separator="cell"
                  hide-bottom
                  :rows-per-page-options="[0]"
                  :pagination="{ rowsPerPage: 0 }"
                  :columns="detailColumns"
                  :rows="props.row.detail"
                  class="my-sticky-child"
                ></q-table>
                <div v-else class="text-orange">
                  <q-icon name="warning" />无相似数据
                </div>
              </div>
            </q-td>
          </q-tr>
        </template>
      </q-table>

      <div class="text-blue text-bold text-center q-pa-md" style="font-size: 1.2em;">
        <q-icon name="information" />提示：请勾选需要输入的数据
      </div>
      <q-stepper-navigation class="flex justify-center">
        <q-btn color="primary" @click="doImport" label="数据导入" :disable="selected.length === 0" />
        <q-btn flat @click="step = 2" color="primary" label="上一步" class="q-ml-sm" />
        <q-btn label="返回" @click="goBack" color="primary" outline class="q-ml-md bg-white" />
      </q-stepper-navigation>
    </q-step>
  </q-stepper>

</template>

<script>
import { defineComponent } from 'vue';
import { mapState, mapActions } from 'pinia';
import { useStore } from 'stores/store';
import readFromFile from 'components/importUtils/readFromFile.vue';
import previewData from 'components/importUtils/previewData.vue';

export default defineComponent({
  components: {
    readFromFile,
    previewData
  },
  inject: ['sendCooperation', 'confirmBox'],
  data () {
    return {
      step: 1,
      fields: [
        { value: 'material_no', label: '货物编码', required: true, column: 'A' },
        { value: 'material_name', label: '货物名称', required: true, column: 'B' },
        { value: 'material_model', label: '货物规格', column: 'C' },
        { value: 'material', label: '材质或色号', column: '' },
        { value: 'material_unit', label: '单位', column: 'D' },
        { value: 'sale_price', label: '销售单价', column: 'E' },
        { value: 'brand', label: '品牌', column: '' },
        { value: 'origin', label: '产地', column: '' },
        { value: 'remark', label: '备注', column: '' }
      ],
      data: [],
      selected: [],
      pagination: {
        sortBy: 'id',
        descending: false,
        page: 1,
        rowsPerPage: 0
        // rowsNumber: 10
      },
      simStandard: 0.6,
      loading: false,
      progress: 0
    }
  },
  async mounted () {
    this.$storage.get('materialSimStandard', true).then(ret => {
      if (ret) {
        this.simStandard = ret;
      }
    });
  },
  methods: {
    goBack () {
      this.$router.push({ path: `/main/${this.$route.path.split('/')[2]}`, query: { back: 'true' } });
    },
    step1 () { // 第一步
      this.$refs.readFile.do().then(data => {
        if (data) {
          this.step = 2;
          this.$nextTick(() => {
            this.$refs.preview && this.$refs.preview.previewData({ ...data, fields: this.fields });
          });
        }
      });
    },
    step2 () { // 第二步
      const data = this.$refs.preview.validateData();

      if (data.result === 'fail') {
        this.$q.notify({
          message: '数据空值校验未通过，调整后重新导入',
          color: 'negative',
          icon: 'error',
          position: 'top',
          timeout: 2000
        });
      } else {
        this.step = 3;
        this.$nextTick(() => {
          this.similarity(data.data);
        });
      }
    },
    similarity (data) { // 匹配相似数据
      this.loading = true;
      this.$axios.post('/c2/tenant/material/findSimilar', { data, standard: this.simStandard }).then(({ data }) => {
        this.data = data;
        this.selected = data.filter(v => v.detail.length === 0);
        this.loading = false;
      });
    },
    doImport () {
      this.confirmBox('询问', `确定把${this.selected.length}条数据导入吗？`).then(confirm => {
        if (confirm) {
          const formData = [];
          for (const row of this.selected) {
            const { material_no, material_name, material_model, material, material_unit, sale_price, brand, origin, remark } = row;
            formData.push({
              material_no: String(material_no || '').trim(),
              material_name: String(material_name || '').trim(),
              material_model: String(material_model || '').trim(),
              material: String(material || '').trim(),
              material_unit: String(material_unit || '').trim(),
              sale_price: String(sale_price || '0').trim(),
              brand: String(brand || '').trim(),
              origin: String(origin || '').trim(),
              remark: String(remark || '').trim()
            });
          }
          this.$axios.post('/c2/tenant/material/doImport', { data: formData, catalog: this.$route.query }).then((res) => {
            if (res.data.result === 'fail') {
              this.$q.notify({
                message: res.data.message || '数据导入失败',
                color: 'negative',
                icon: 'error',
                position: 'top',
                timeout: 5000,
                html: res.data.message && res.data.message.indexOf('<br>') >= 0
              });
            } else {
              this.$q.notify({
                message: res.data.message || '数据导入成功',
                color: 'secondary',
                icon: 'done',
                position: 'top',
                timeout: 2000
              });
              // 发送协同，刷新字典
              this.sendCooperation({ type: 'refresh_dict', data: ['material'] });
              // this.$router.go(-1);
              this.goBack();
            }
          });
        }
      });
    },
    checkDisabled (row) {
      // 是否有相似度为1的数据
      return row.detail && row.detail.filter(v => Number(v.similarity) === 1).length > 0
    }
  },
  computed: {
    ...mapState(useStore, ['dictionary']),
    columns () { // 第3步的字段
      return this.fields.map(field => ({
        name: field.value,
        label: field.label,
        field: field.value,
        align: 'center'
      }));
    },
    detailColumns () { // 第3步相似数据的字段
      return [
        { name: 'id', label: '序号', field: 'id', align: 'center' },
        ...this.fields.map(field => ({
          name: field.value,
          label: field.label,
          field: field.value,
          align: 'center'
        })), { name: 'similarity', label: '相似度', field: 'similarity', align: 'center' }];
    }
  },
  watch: {
    simStandard (val) {
      this.$storage.set('materialSimStandard', val, true);
    }
  }
});
</script>
